Skip to contentSkip to conversation

python3-django: Fix CVE-2024-38875

PATCH New ssambu 1 participant 10 messages Jan 10, 2025

lore
Share & tools
lore

ssambu

author
#0 lore raw

PATCH 1/9 python3-django: Fix CVE-2024-38875

From: Soumya Sambu <[email protected]>

An issue was discovered in Django 4.2 before 4.2.14 and 5.0 before 5.0.7. urlize and urlizetrunc were subject to a potential denial of service attack via certain inputs with a very large number of brackets.

References:
https://nvd.nist.gov/vuln/detail/CVE-2024-38875
https://github.com/advisories/GHSA-qg2p-9jwr-mmqf

Upstream-patch:
https://github.com/django/django/commit/79f368764295df109a37192f6182fb6f361d85b5

---
 .../python3-django/CVE-2024-38875.patch       | 161 ++++++++++++++++++
 .../python/python3-django_2.2.28.bb           |   1 +
 2 files changed, 162 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-django/CVE-2024-38875.patch
meta-python/recipes-devtools/python/python3-django/CVE-2024-38875.patch new file +161 -0
new file mode 100644
index 000000000..8ccb888c6
@@ -0,0 +1,161 @@
+From 79f368764295df109a37192f6182fb6f361d85b5 Mon Sep 17 00:00:00 2001
+From: Adam Johnson <[email protected]>
+Date: Mon, 24 Jun 2024 15:30:59 +0200
+Subject: [PATCH] [4.2.x] Fixed CVE-2024-38875 -- Mitigated potential DoS in
+ urlize and urlizetrunc template filters.
+
+Thank you to Elias Myllymäki for the report.
+
+Co-authored-by: Sarah Boyce <[email protected]>
+
+CVE: CVE-2024-38875
+
+Upstream-Status: Backport [https://github.com/django/django/commit/79f368764295df109a37192f6182fb6f361d85b5]
+
+Signed-off-by: Soumya Sambu <[email protected]>
+---
+ django/utils/html.py           | 90 +++++++++++++++++++++++++---------
+ tests/utils_tests/test_html.py |  7 +++
+ 2 files changed, 73 insertions(+), 21 deletions(-)
+
+diff --git a/django/utils/html.py b/django/utils/html.py
+index 7a33d5f..f1b74ab 100644
+--- a/django/utils/html.py
++++ b/django/utils/html.py
+@@ -234,6 +234,15 @@ def smart_urlquote(url):
+
+     return urlunsplit((scheme, netloc, path, query, fragment))
+
++class CountsDict(dict):
++    def __init__(self, *args, word, **kwargs):
++        super().__init__(*args, *kwargs)
++        self.word = word
++
++    def __missing__(self, key):
++        self[key] = self.word.count(key)
++        return self[key]
++
+
+ @keep_lazy_text
+ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
+@@ -268,36 +277,69 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
+         return text.replace('&amp;', '&').replace('&lt;', '<').replace(
+             '&gt;', '>').replace('&quot;', '"').replace('&#39;', "'")
+
+-    def trim_punctuation(lead, middle, trail):
++    def wrapping_punctuation_openings():
++        return "".join(dict(WRAPPING_PUNCTUATION).keys())
++
++    def trailing_punctuation_chars_no_semicolon():
++        return TRAILING_PUNCTUATION_CHARS.replace(";", "")
++
++    def trailing_punctuation_chars_has_semicolon():
++        return ";" in TRAILING_PUNCTUATION_CHARS
++
++    def trim_punctuation(word):
+         """
+         Trim trailing and wrapping punctuation from `middle`. Return the items
+         of the new state.
+         """
++        # Strip all opening wrapping punctuation.
++        middle = word.lstrip(wrapping_punctuation_openings())
++        lead = word[: len(word) - len(middle)]
++        trail = ""
++
+         # Continue trimming until middle remains unchanged.
+         trimmed_something = True
+-        while trimmed_something:
++        counts = CountsDict(word=middle)
++        while trimmed_something and middle:
+             trimmed_something = False
+             # Trim wrapping punctuation.
+             for opening, closing in WRAPPING_PUNCTUATION:
+-                if middle.startswith(opening):
+-                    middle = middle[len(opening):]
+-                    lead += opening
+-                    trimmed_something = True
+-                # Keep parentheses at the end only if they're balanced.
+-                if (middle.endswith(closing) and
+-                        middle.count(closing) == middle.count(opening) + 1):
+-                    middle = middle[:-len(closing)]
+-                    trail = closing + trail
+-                    trimmed_something = True
+-            # Trim trailing punctuation (after trimming wrapping punctuation,
+-            # as encoded entities contain ';'). Unescape entites to avoid
+-            # breaking them by removing ';'.
+-            middle_unescaped = unescape(middle)
+-            stripped = middle_unescaped.rstrip(TRAILING_PUNCTUATION_CHARS)
+-            if middle_unescaped != stripped:
+-                trail = middle[len(stripped):] + trail
+-                middle = middle[:len(stripped) - len(middle_unescaped)]
++                if counts[opening] < counts[closing]:
++                    rstripped = middle.rstrip(closing)
++                    if rstripped != middle:
++                        strip = counts[closing] - counts[opening]
++                        trail = middle[-strip:]
++                        middle = middle[:-strip]
++                        trimmed_something = True
++                        counts[closing] -= strip
++
++            rstripped = middle.rstrip(trailing_punctuation_chars_no_semicolon())
++            if rstripped != middle:
++                trail = middle[len(rstripped) :] + trail
++                middle = rstripped
+                 trimmed_something = True
++
++            if trailing_punctuation_chars_has_semicolon() and middle.endswith(";"):
++                # Only strip if not part of an HTML entity.
++                amp = middle.rfind("&")
++                if amp == -1:
++                    can_strip = True
++                else:
++                    potential_entity = middle[amp:]
++                    escaped = unescape(potential_entity)
++                    can_strip = (escaped == potential_entity) or escaped.endswith(";")
++
++                if can_strip:
++                    rstripped = middle.rstrip(";")
++                    amount_stripped = len(middle) - len(rstripped)
++                    if amp > -1 and amount_stripped > 1:
++                        # Leave a trailing semicolon as might be an entity.
++                        trail = middle[len(rstripped) + 1 :] + trail
++                        middle = rstripped + ";"
++                    else:
++                        trail = middle[len(rstripped) :] + trail
++                        middle = rstripped
++                    trimmed_something = True
++
+         return lead, middle, trail
+
+     def is_email_simple(value):
+@@ -321,9 +363,7 @@ def urlize(text, trim_url_limit=None, no
+             # lead: Current punctuation trimmed from the beginning of the word.
+             # middle: Current state of the word.
+             # trail: Current punctuation trimmed from the end of the word.
+-            lead, middle, trail = '', word, ''
+-            # Deal with punctuation.
+-            lead, middle, trail = trim_punctuation(lead, middle, trail)
++            lead, middle, trail = trim_punctuation(word)
+
+             # Make URL we want to point to.
+             url = None
+diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py
+index 5cc2d9b..715c1c6 100644
+--- a/tests/utils_tests/test_html.py
++++ b/tests/utils_tests/test_html.py
+@@ -267,6 +267,13 @@ class TestUtilsHtml(SimpleTestCase):
+             '[email protected]',
+             'foo@localhost',
+             'foo@localhost.',
++            # trim_punctuation catastrophic tests
++            "(" * 100_000 + ":" + ")" * 100_000,
++            "(" * 100_000 + "&:" + ")" * 100_000,
++            "([" * 100_000 + ":" + "])" * 100_000,
++            "[(" * 100_000 + ":" + ")]" * 100_000,
++            "([[" * 100_000 + ":" + "]])" * 100_000,
++            "&:" + ";" * 100_000,
+         )
+         for value in tests:
+             with self.subTest(value=value):
+--
+2.40.0
meta-python/recipes-devtools/python/python3-django_2.2.28.bb +1 -0
index 7f5861f5d..f082de9d7 100644
@@ -12,6 +12,7 @@ SRC_URI += "file://CVE-2023-31047.patch \
             file://CVE-2023-46695.patch \
             file://CVE-2024-24680.patch \
             file://CVE-2024-42005.patch \
+            file://CVE-2024-38875.patch \
            "
 
 SRC_URI[sha256sum] = "0200b657afbf1bc08003845ddda053c7641b9b24951e52acd51f6abda33a7413"
Signature · 1 line
2.40.0
author
#1 lore raw

PATCH 1/1 python3-django: upgrade 4.2.15 -> 4.2.17

From: Soumya Sambu <[email protected]>

Fixes CVE-2024-45230, CVE-2024-45231, CVE-2024-53907 and CVE-2024-53908

Release Notes:
https://docs.djangoproject.com/en/dev/releases/4.2.16/
https://docs.djangoproject.com/en/dev/releases/4.2.17/

---
 .../{python3-django_4.2.15.bb => python3-django_4.2.17.bb}    | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
 rename meta-python/recipes-devtools/python/{python3-django_4.2.15.bb => python3-django_4.2.17.bb} (61%)
meta-python/recipes-devtools/python/python3-django_4.2.17.bb renamed from meta-python/recipes-devtools/python/python3-django_4.2.15.bb +2 -2
similarity index 61%
rename from meta-python/recipes-devtools/python/python3-django_4.2.15.bb
rename to meta-python/recipes-devtools/python/python3-django_4.2.17.bb
index bf19e91e0..dfce4b85c 100644
@@ -1,7 +1,7 @@
 require python-django.inc
 inherit setuptools3
 
-SRC_URI[sha256sum] = "c77f926b81129493961e19c0e02188f8d07c112a1162df69bfab178ae447f94a"
+SRC_URI[sha256sum] = "6b56d834cc94c8b21a8f4e775064896be3b4a4ca387f2612d4406a5927cd2fdc"
 
 RDEPENDS:${PN} += "\
     ${PYTHON_PN}-sqlparse \
@@ -9,5 +9,5 @@ RDEPENDS:${PN} += "\
 
 # Set DEFAULT_PREFERENCE so that the LTS version of django is built by
 # default. To build the 4.x branch, 
-# PREFERRED_VERSION_python3-django = "4.2.15" can be added to local.conf
+# PREFERRED_VERSION_python3-django = "4.2.17" can be added to local.conf
 DEFAULT_PREFERENCE = "-1"
Signature · 1 line
2.40.0
author
#2 lore raw

PATCH 2/9 python3-django: Fix CVE-2023-23969

In reply to ssambu

From: Soumya Sambu <[email protected]>

In Django 3.2 before 3.2.17, 4.0 before 4.0.9, and 4.1 before 4.1.6, the parsed values of Accept-Language headers are cached in order to avoid repetitive parsing. This leads to a potential denial-of-service vector via excessive memory usage if the raw value of Accept-Language headers is very large.

References:
https://nvd.nist.gov/vuln/detail/CVE-2023-23969

Upstream-patch:
https://github.com/django/django/commit/c7e0151fdf33e1b11d488b6f67b94fdf3a30614a

---
 .../python3-django/CVE-2023-23969.patch       | 108 ++++++++++++++++++
 .../python/python3-django_2.2.28.bb           |   1 +
 2 files changed, 109 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-django/CVE-2023-23969.patch
meta-python/recipes-devtools/python/python3-django/CVE-2023-23969.patch new file +108 -0
new file mode 100644
index 000000000..42e25ad3b
@@ -0,0 +1,108 @@
+From c7e0151fdf33e1b11d488b6f67b94fdf3a30614a Mon Sep 17 00:00:00 2001
+From: Nick Pope <[email protected]>
+Date: Wed, 25 Jan 2023 12:21:48 +0100
+Subject: [PATCH] [3.2.x] Fixed CVE-2023-23969 -- Prevented DoS with
+ pathological values for Accept-Language.
+
+The parsed values of Accept-Language headers are cached in order to
+avoid repetitive parsing. This leads to a potential denial-of-service
+vector via excessive memory usage if the raw value of Accept-Language
+headers is very large.
+
+Accept-Language headers are now limited to a maximum length in order
+to avoid this issue.
+
+CVE: CVE-2023-23969
+
+Upstream-Status: Backport [https://github.com/django/django/commit/c7e0151fdf33e1b11d488b6f67b94fdf3a30614a]
+
+Signed-off-by: Soumya Sambu <[email protected]>
+---
+ django/utils/translation/trans_real.py | 30 +++++++++++++++++++++++++-
+ tests/i18n/tests.py                    | 12 +++++++++++
+ 2 files changed, 41 insertions(+), 1 deletion(-)
+
+diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py
+index 486b2b2..7f658cf 100644
+--- a/django/utils/translation/trans_real.py
++++ b/django/utils/translation/trans_real.py
+@@ -29,6 +29,10 @@ _default = None
+ # magic gettext number to separate context from message
+ CONTEXT_SEPARATOR = "\x04"
+
++# Maximum number of characters that will be parsed from the Accept-Language
++# header to prevent possible denial of service or memory exhaustion attacks.
++ACCEPT_LANGUAGE_HEADER_MAX_LENGTH = 500
++
+ # Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9
+ # and RFC 3066, section 2.1
+ accept_language_re = re.compile(r'''
+@@ -560,7 +564,7 @@ def get_language_from_request(request, check_path=False):
+
+
+ @functools.lru_cache(maxsize=1000)
+-def parse_accept_lang_header(lang_string):
++def _parse_accept_lang_header(lang_string):
+     """
+     Parse the lang_string, which is the body of an HTTP Accept-Language
+     header, and return a tuple of (lang, q-value), ordered by 'q' values.
+@@ -582,3 +586,27 @@ def parse_accept_lang_header(lang_string):
+         result.append((lang, priority))
+     result.sort(key=lambda k: k[1], reverse=True)
+     return tuple(result)
++
++
++def parse_accept_lang_header(lang_string):
++    """
++    Parse the value of the Accept-Language header up to a maximum length.
++
++    The value of the header is truncated to a maximum length to avoid potential
++    denial of service and memory exhaustion attacks. Excessive memory could be
++    used if the raw value is very large as it would be cached due to the use of
++    `functools.lru_cache()` to avoid repetitive parsing of common header values.
++    """
++    # If the header value doesn't exceed the maximum allowed length, parse it.
++    if len(lang_string) <= ACCEPT_LANGUAGE_HEADER_MAX_LENGTH:
++        return _parse_accept_lang_header(lang_string)
++
++    # If there is at least one comma in the value, parse up to the last comma,
++    # skipping any truncated parts at the end of the header value.
++    index = lang_string.rfind(",", 0, ACCEPT_LANGUAGE_HEADER_MAX_LENGTH)
++    if index > 0:
++        return _parse_accept_lang_header(lang_string[:index])
++
++    # Don't attempt to parse if there is only one language-range value which is
++    # longer than the maximum allowed length and so truncated.
++    return ()
+diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py
+index 7381cb9..6efc3a5 100644
+--- a/tests/i18n/tests.py
++++ b/tests/i18n/tests.py
+@@ -1282,6 +1282,14 @@ class MiscTests(SimpleTestCase):
+             ('de;q=0.', [('de', 0.0)]),
+             ('en; q=1,', [('en', 1.0)]),
+             ('en; q=1.0, * ; q=0.5', [('en', 1.0), ('*', 0.5)]),
++            (
++                'en' + '-x' * 20,
++                [('en-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x', 1.0)],
++            ),
++            (
++                ', '.join(['en; q=1.0'] * 20),
++                [('en', 1.0)] * 20,
++            ),
+             # Bad headers
+             ('en-gb;q=1.0000', []),
+             ('en;q=0.1234', []),
+@@ -1297,6 +1305,10 @@ class MiscTests(SimpleTestCase):
+             ('12-345', []),
+             ('', []),
+             ('en;q=1e0', []),
++            # Invalid as language-range value too long.
++            ('xxxxxxxx' + '-xxxxxxxx' * 500, []),
++            # Header value too long, only parse up to limit.
++            (', '.join(['en; q=1.0'] * 500), [('en', 1.0)] * 45),
+         ]
+         for value, expected in tests:
+             with self.subTest(value=value):
+--
+2.40.0
meta-python/recipes-devtools/python/python3-django_2.2.28.bb +1 -0
index f082de9d7..d8fc147f1 100644
@@ -13,6 +13,7 @@ SRC_URI += "file://CVE-2023-31047.patch \
             file://CVE-2024-24680.patch \
             file://CVE-2024-42005.patch \
             file://CVE-2024-38875.patch \
+            file://CVE-2023-23969.patch \
            "
 
 SRC_URI[sha256sum] = "0200b657afbf1bc08003845ddda053c7641b9b24951e52acd51f6abda33a7413"
Signature · 1 line
2.40.0
author
#3 lore raw

PATCH 3/9 python3-django: Fix CVE-2024-39614

In reply to ssambu

From: Soumya Sambu <[email protected]>

An issue was discovered in Django 5.0 before 5.0.7 and 4.2 before 4.2.14. get_supported_language_variant() was subject to a potential denial-of-service attack when used with very long strings containing specific characters.

Reference:
https://nvd.nist.gov/vuln/detail/CVE-2024-39614

Upstream-patch:
https://github.com/django/django/commit/17358fb35fb7217423d4c4877ccb6d1a3a40b1c3

---
 .../python3-django/CVE-2024-39614.patch       | 138 ++++++++++++++++++
 .../python/python3-django_2.2.28.bb           |   1 +
 2 files changed, 139 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-django/CVE-2024-39614.patch
meta-python/recipes-devtools/python/python3-django/CVE-2024-39614.patch new file +138 -0
new file mode 100644
index 000000000..340cfceac
@@ -0,0 +1,138 @@
+From 17358fb35fb7217423d4c4877ccb6d1a3a40b1c3 Mon Sep 17 00:00:00 2001
+From: Sarah Boyce <[email protected]>
+Date: Wed, 26 Jun 2024 12:11:54 +0200
+Subject: [PATCH] [4.2.x] Fixed CVE-2024-39614 -- Mitigated potential DoS in
+ get_supported_language_variant().
+
+Language codes are now parsed with a maximum length limit of 500 chars.
+
+Thanks to MProgrammer for the report.
+
+CVE: CVE-2024-39614
+
+Upstream-Status: Backport [https://github.com/django/django/commit/17358fb35fb7217423d4c4877ccb6d1a3a40b1c3]
+
+Signed-off-by: Soumya Sambu <[email protected]>
+---
+ django/utils/translation/trans_real.py | 24 ++++++++++++++++++++----
+ docs/ref/utils.txt                     | 10 ++++++++++
+ tests/i18n/tests.py                    | 11 +++++++++++
+ 3 files changed, 41 insertions(+), 4 deletions(-)
+
+diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py
+index 7f658cf..56b4ef1 100644
+--- a/django/utils/translation/trans_real.py
++++ b/django/utils/translation/trans_real.py
+@@ -30,8 +30,10 @@ _default = None
+ CONTEXT_SEPARATOR = "\x04"
+
+ # Maximum number of characters that will be parsed from the Accept-Language
+-# header to prevent possible denial of service or memory exhaustion attacks.
+-ACCEPT_LANGUAGE_HEADER_MAX_LENGTH = 500
++# header or cookie to prevent possible denial of service or memory exhaustion
++# attacks. About 10x longer than the longest value shown on MDN’s
++# Accept-Language page.
++LANGUAGE_CODE_MAX_LENGTH = 500
+
+ # Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9
+ # and RFC 3066, section 2.1
+@@ -472,11 +474,25 @@ def get_supported_language_variant(lang_code, strict=False):
+     If `strict` is False (the default), look for a country-specific variant
+     when neither the language code nor its generic variant is found.
+
++    The language code is truncated to a maximum length to avoid potential
++    denial of service attacks.
++
+     lru_cache should have a maxsize to prevent from memory exhaustion attacks,
+     as the provided language codes are taken from the HTTP request. See also
+     <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
+     """
+     if lang_code:
++        # Truncate the language code to a maximum length to avoid potential
++        # denial of service attacks.
++        if len(lang_code) > LANGUAGE_CODE_MAX_LENGTH:
++            if (
++                not strict
++                and (index := lang_code.rfind("-", 0, LANGUAGE_CODE_MAX_LENGTH)) > 0
++            ):
++                # There is a generic variant under the maximum length accepted length.
++                lang_code = lang_code[:index]
++            else:
++                raise ValueError("'lang_code' exceeds the maximum accepted length")
+         # If 'fr-ca' is not supported, try special fallback or language-only 'fr'.
+         possible_lang_codes = [lang_code]
+         try:
+@@ -598,12 +614,12 @@ def parse_accept_lang_header(lang_string):
+     `functools.lru_cache()` to avoid repetitive parsing of common header values.
+     """
+     # If the header value doesn't exceed the maximum allowed length, parse it.
+-    if len(lang_string) <= ACCEPT_LANGUAGE_HEADER_MAX_LENGTH:
++    if len(lang_string) <= LANGUAGE_CODE_MAX_LENGTH:
+         return _parse_accept_lang_header(lang_string)
+
+     # If there is at least one comma in the value, parse up to the last comma,
+     # skipping any truncated parts at the end of the header value.
+-    index = lang_string.rfind(",", 0, ACCEPT_LANGUAGE_HEADER_MAX_LENGTH)
++    index = lang_string.rfind(",", 0, LANGUAGE_CODE_MAX_LENGTH)
+     if index > 0:
+         return _parse_accept_lang_header(lang_string[:index])
+
+diff --git a/docs/ref/utils.txt b/docs/ref/utils.txt
+index 390f167..63a56e5 100644
+--- a/docs/ref/utils.txt
++++ b/docs/ref/utils.txt
+@@ -1142,6 +1142,11 @@ functions without the ``u``.
+     ``lang_code`` is ``'es-ar'`` and ``'es'`` is in :setting:`LANGUAGES` but
+     ``'es-ar'`` isn't.
+
++    ``lang_code`` has a maximum accepted length of 500 characters. A
++    :exc:`ValueError` is raised if ``lang_code`` exceeds this limit and
++    ``strict`` is ``True``, or if there is no generic variant and ``strict``
++    is ``False``.
++
+     If ``strict`` is ``False`` (the default), a country-specific variant may
+     be returned when neither the language code nor its generic variant is found.
+     For example, if only ``'es-co'`` is in :setting:`LANGUAGES`, that's
+@@ -1150,6 +1155,11 @@ functions without the ``u``.
+
+     Raises :exc:`LookupError` if nothing is found.
+
++    .. versionchanged:: 4.2.14
++
++        In older versions, ``lang_code`` values over 500 characters were
++        processed without raising a :exc:`ValueError`.
++
+ .. function:: to_locale(language)
+
+     Turns a language name (en-us) into a locale name (en_US).
+diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py
+index 6efc3a5..0e93395 100644
+--- a/tests/i18n/tests.py
++++ b/tests/i18n/tests.py
+@@ -39,6 +39,7 @@ from django.utils.translation import (
+ from django.utils.translation.reloader import (
+     translation_file_changed, watch_for_translation_changes,
+ )
++from django.utils.translation.trans_real import LANGUAGE_CODE_MAX_LENGTH
+
+ from .forms import CompanyForm, I18nForm, SelectDateForm
+ from .models import Company, TestModel
+@@ -1462,6 +1463,16 @@ class MiscTests(SimpleTestCase):
+             g('xyz')
+         with self.assertRaises(LookupError):
+             g('xy-zz')
++        msg = "'lang_code' exceeds the maximum accepted length"
++        with self.assertRaises(LookupError):
++            g("x" * LANGUAGE_CODE_MAX_LENGTH)
++        with self.assertRaisesMessage(ValueError, msg):
++            g("x" * (LANGUAGE_CODE_MAX_LENGTH + 1))
++        # 167 * 3 = 501 which is LANGUAGE_CODE_MAX_LENGTH + 1.
++        self.assertEqual(g("en-" * 167), "en")
++        with self.assertRaisesMessage(ValueError, msg):
++            g("en-" * 167, strict=True)
++        self.assertEqual(g("en-" * 30000), "en")  # catastrophic test
+
+     def test_get_supported_language_variant_null(self):
+         g = trans_null.get_supported_language_variant
+--
+2.40.0
meta-python/recipes-devtools/python/python3-django_2.2.28.bb +1 -0
index d8fc147f1..d06f48b1b 100644
@@ -14,6 +14,7 @@ SRC_URI += "file://CVE-2023-31047.patch \
             file://CVE-2024-42005.patch \
             file://CVE-2024-38875.patch \
             file://CVE-2023-23969.patch \
+            file://CVE-2024-39614.patch \
            "
 
 SRC_URI[sha256sum] = "0200b657afbf1bc08003845ddda053c7641b9b24951e52acd51f6abda33a7413"
Signature · 1 line
2.40.0
author
#4 lore raw

PATCH 4/9 python3-django: Fix CVE-2024-41989

In reply to ssambu

From: Soumya Sambu <[email protected]>

An issue was discovered in Django 5.0 before 5.0.8 and 4.2 before 4.2.15. The floatformat template filter is subject to significant memory consumption when given a string representation of a number in scientific notation with a large exponent.

Reference:
https://nvd.nist.gov/vuln/detail/CVE-2024-41989

Upstream-patches:
https://github.com/django/django/commit/08c5a787262c1ae57f6517d4574b54a5fcaad124
https://github.com/django/django/commit/4b066bde692078b194709d517b27e55defae787c
https://github.com/django/django/commit/dcd974698301a38081c141ccba6dcafa5ed2c80e
https://github.com/django/django/commit/fc76660f589ac07e45e9cd34ccb8087aeb11904b

---
 .../python3-django/CVE-2024-41989-0001.patch  | 48 +++++++++++
 .../python3-django/CVE-2024-41989-0002.patch  | 48 +++++++++++
 .../python3-django/CVE-2024-41989-0003.patch  | 57 +++++++++++++
 .../python3-django/CVE-2024-41989-0004.patch  | 81 +++++++++++++++++++
 .../python/python3-django_2.2.28.bb           |  4 +
 5 files changed, 238 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-django/CVE-2024-41989-0001.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-django/CVE-2024-41989-0002.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-django/CVE-2024-41989-0003.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-django/CVE-2024-41989-0004.patch
meta-python/recipes-devtools/python/python3-django/CVE-2024-41989-0001.patch new file +48 -0
new file mode 100644
index 000000000..04c0cf91e
@@ -0,0 +1,48 @@
+From 08c5a787262c1ae57f6517d4574b54a5fcaad124 Mon Sep 17 00:00:00 2001
+From: Vlastimil Zíma <[email protected]>
+Date: Mon, 24 Oct 2022 12:59:34 +0200
+Subject: [PATCH] Fixed #34098 -- Fixed loss of precision for Decimal values in
+  floatformat filter.
+
+Regression in 12f7928f5a455e330c0a7f19bc86b37baca12811.
+
+CVE: CVE-2024-41989
+
+Upstream-Status: Backport [https://github.com/django/django/commit/08c5a787262c1ae57f6517d4574b54a5fcaad124]
+
+Signed-off-by: Soumya Sambu <[email protected]>
+---
+ django/template/defaultfilters.py                     | 2 +-
+ tests/template_tests/filter_tests/test_floatformat.py | 4 ++++
+ 2 files changed, 5 insertions(+), 1 deletion(-)
+
+diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
+index a1d77f5..9ca530c 100644
+--- a/django/template/defaultfilters.py
++++ b/django/template/defaultfilters.py
+@@ -123,7 +123,7 @@ def floatformat(text, arg=-1):
+     of that value.
+     """
+     try:
+-        input_val = repr(text)
++        input_val = str(text)
+         d = Decimal(input_val)
+     except InvalidOperation:
+         try:
+diff --git a/tests/template_tests/filter_tests/test_floatformat.py b/tests/template_tests/filter_tests/test_floatformat.py
+index cfc3eaf..acad66d 100644
+--- a/tests/template_tests/filter_tests/test_floatformat.py
++++ b/tests/template_tests/filter_tests/test_floatformat.py
+@@ -44,6 +44,10 @@ class FunctionTests(SimpleTestCase):
+         self.assertEqual(floatformat(0.12345, 2), '0.12')
+         self.assertEqual(floatformat(Decimal('555.555'), 2), '555.56')
+         self.assertEqual(floatformat(Decimal('09.000')), '9')
++        self.assertEqual(
++            floatformat(Decimal("123456.123456789012345678901"), 21),
++            "123456.123456789012345678901",
++        )
+         self.assertEqual(floatformat('foo'), '')
+         self.assertEqual(floatformat(13.1031, 'bar'), '13.1031')
+         self.assertEqual(floatformat(18.125, 2), '18.13')
+--
+2.40.0
meta-python/recipes-devtools/python/python3-django/CVE-2024-41989-0002.patch new file +48 -0

48 lines not on this page · raw message

meta-python/recipes-devtools/python/python3-django/CVE-2024-41989-0003.patch new file +57 -0

57 lines not on this page · raw message

meta-python/recipes-devtools/python/python3-django/CVE-2024-41989-0004.patch new file +81 -0

81 lines not on this page · raw message

meta-python/recipes-devtools/python/python3-django_2.2.28.bb +4 -0
index d06f48b1b..dc7e12ad7 100644
@@ -15,6 +15,10 @@ SRC_URI += "file://CVE-2023-31047.patch \
             file://CVE-2024-38875.patch \
             file://CVE-2023-23969.patch \
             file://CVE-2024-39614.patch \
+            file://CVE-2024-41989-0001.patch \
+            file://CVE-2024-41989-0002.patch \
+            file://CVE-2024-41989-0003.patch \
+            file://CVE-2024-41989-0004.patch \
            "
 
 SRC_URI[sha256sum] = "0200b657afbf1bc08003845ddda053c7641b9b24951e52acd51f6abda33a7413"
Signature · 1 line
2.40.0
author
#5 lore raw

PATCH 5/9 python3-django: Fix CVE-2024-41990

In reply to ssambu

From: Soumya Sambu <[email protected]>

An issue was discovered in Django 5.0 before 5.0.8 and 4.2 before 4.2.15. The urlize() and urlizetrunc() template filters are subject to a potential denial-of-service attack via very large inputs with a specific sequence of characters.

Reference:
https://nvd.nist.gov/vuln/detail/CVE-2024-41990

Upstream-patch:
https://github.com/django/django/commit/d0a82e26a74940bf0c78204933c3bdd6a283eb88

---
 .../python3-django/CVE-2024-41990.patch       | 69 +++++++++++++++++++
 .../python/python3-django_2.2.28.bb           |  1 +
 2 files changed, 70 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-django/CVE-2024-41990.patch
meta-python/recipes-devtools/python/python3-django/CVE-2024-41990.patch new file +69 -0
new file mode 100644
index 000000000..f4be19520
@@ -0,0 +1,69 @@
+From d0a82e26a74940bf0c78204933c3bdd6a283eb88 Mon Sep 17 00:00:00 2001
+From: Sarah Boyce <[email protected]>
+Date: Thu, 18 Jul 2024 13:19:34 +0200
+Subject: [PATCH] [4.2.x] Fixed CVE-2024-41990 -- Mitigated potential DoS in
+ urlize and urlizetrunc template filters.
+
+Thanks to MProgrammer for the report.
+
+CVE: CVE-2024-41990
+
+Upstream-Status: Backport [https://github.com/django/django/commit/d0a82e26a74940bf0c78204933c3bdd6a283eb88]
+
+Signed-off-by: Soumya Sambu <[email protected]>
+---
+ django/utils/html.py           | 18 ++++++++----------
+ tests/utils_tests/test_html.py |  2 ++
+ 2 files changed, 10 insertions(+), 10 deletions(-)
+
+diff --git a/django/utils/html.py b/django/utils/html.py
+index f1b74ab..84e157d 100644
+--- a/django/utils/html.py
++++ b/django/utils/html.py
+@@ -315,7 +315,11 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
+                         trimmed_something = True
+                         counts[closing] -= strip
+
+-            rstripped = middle.rstrip(trailing_punctuation_chars_no_semicolon())
++            amp = middle.rfind("&")
++            if amp == -1:
++                rstripped = middle.rstrip(TRAILING_PUNCTUATION_CHARS)
++            else:
++                rstripped = middle.rstrip(trailing_punctuation_chars_no_semicolon())
+             if rstripped != middle:
+                 trail = middle[len(rstripped) :] + trail
+                 middle = rstripped
+@@ -323,15 +327,9 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
+
+             if trailing_punctuation_chars_has_semicolon() and middle.endswith(";"):
+                 # Only strip if not part of an HTML entity.
+-                amp = middle.rfind("&")
+-                if amp == -1:
+-                    can_strip = True
+-                else:
+-                    potential_entity = middle[amp:]
+-                    escaped = unescape(potential_entity)
+-                    can_strip = (escaped == potential_entity) or escaped.endswith(";")
+-
+-                if can_strip:
++                potential_entity = middle[amp:]
++                escaped = unescape(potential_entity)
++                if escaped == potential_entity or escaped.endswith(";"):
+                     rstripped = middle.rstrip(";")
+                     amount_stripped = len(middle) - len(rstripped)
+                     if amp > -1 and amount_stripped > 1:
+diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py
+index 715c1c6..5abab8d 100644
+--- a/tests/utils_tests/test_html.py
++++ b/tests/utils_tests/test_html.py
+@@ -274,6 +274,8 @@ class TestUtilsHtml(SimpleTestCase):
+             "[(" * 100_000 + ":" + ")]" * 100_000,
+             "([[" * 100_000 + ":" + "]])" * 100_000,
+             "&:" + ";" * 100_000,
++            "&.;" * 100_000,
++            ".;" * 100_000,
+         )
+         for value in tests:
+             with self.subTest(value=value):
+--
+2.40.0
meta-python/recipes-devtools/python/python3-django_2.2.28.bb +1 -0
index dc7e12ad7..57ab72bc9 100644
@@ -19,6 +19,7 @@ SRC_URI += "file://CVE-2023-31047.patch \
             file://CVE-2024-41989-0002.patch \
             file://CVE-2024-41989-0003.patch \
             file://CVE-2024-41989-0004.patch \
+            file://CVE-2024-41990.patch \
            "
 
 SRC_URI[sha256sum] = "0200b657afbf1bc08003845ddda053c7641b9b24951e52acd51f6abda33a7413"
Signature · 1 line
2.40.0
author
#6 lore raw

PATCH 6/9 python3-django: Fix CVE-2024-41991

In reply to ssambu

From: Soumya Sambu <[email protected]>

An issue was discovered in Django 5.0 before 5.0.8 and 4.2 before 4.2.15. The urlize and urlizetrunc template filters, and the AdminURLFieldWidget widget, are subject to a potential denial-of-service attack via certain inputs with a very large number of Unicode characters.

Reference:
https://nvd.nist.gov/vuln/detail/CVE-2024-41991

Upstream-patch:
https://github.com/django/django/commit/efea1ef7e2190e3f77ca0651b5458297bc0f6a9f

---
 .../python3-django/CVE-2024-41991.patch       | 122 ++++++++++++++++++
 .../python/python3-django_2.2.28.bb           |   1 +
 2 files changed, 123 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-django/CVE-2024-41991.patch
meta-python/recipes-devtools/python/python3-django/CVE-2024-41991.patch new file +122 -0
new file mode 100644
index 000000000..c050a4ad3
@@ -0,0 +1,122 @@
+From efea1ef7e2190e3f77ca0651b5458297bc0f6a9f Mon Sep 17 00:00:00 2001
+From: Mariusz Felisiak <[email protected]>
+Date: Wed, 10 Jul 2024 20:30:12 +0200
+Subject: [PATCH] [4.2.x] Fixed CVE-2024-41991 -- Prevented potential ReDoS in
+ django.utils.html.urlize() and AdminURLFieldWidget.
+
+Thanks Seokchan Yoon for the report.
+
+Co-authored-by: Sarah Boyce <[email protected]>
+
+CVE: CVE-2024-41991
+
+Upstream-Status: Backport [https://github.com/django/django/commit/efea1ef7e2190e3f77ca0651b5458297bc0f6a9f]
+
+Signed-off-by: Soumya Sambu <[email protected]>
+---
+ django/contrib/admin/widgets.py |  2 +-
+ django/utils/html.py            | 10 ++++++++--
+ tests/admin_widgets/tests.py    |  7 ++++++-
+ tests/utils_tests/test_html.py  | 13 +++++++++++++
+ 4 files changed, 28 insertions(+), 4 deletions(-)
+
+diff --git a/django/contrib/admin/widgets.py b/django/contrib/admin/widgets.py
+index a56baee..47647e8 100644
+--- a/django/contrib/admin/widgets.py
++++ b/django/contrib/admin/widgets.py
+@@ -344,7 +344,7 @@ class AdminURLFieldWidget(forms.URLInput):
+         context = super().get_context(name, value, attrs)
+         context['current_label'] = _('Currently:')
+         context['change_label'] = _('Change:')
+-        context['widget']['href'] = smart_urlquote(context['widget']['value']) if value else ''
++        context['widget']['href'] = smart_urlquote(context['widget']['value']) if url_valid else ''
+         context['url_valid'] = url_valid
+         return context
+
+diff --git a/django/utils/html.py b/django/utils/html.py
+index 84e157d..52a3389 100644
+--- a/django/utils/html.py
++++ b/django/utils/html.py
+@@ -12,6 +12,8 @@ from django.utils.http import RFC3986_GENDELIMS, RFC3986_SUBDELIMS
+ from django.utils.safestring import SafeData, SafeText, mark_safe
+ from django.utils.text import normalize_newlines
+
++MAX_URL_LENGTH = 2048
++
+ # Configuration for urlize() function.
+ TRAILING_PUNCTUATION_CHARS = '.,:;!'
+ WRAPPING_PUNCTUATION = [('(', ')'), ('[', ']')]
+@@ -353,6 +355,10 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
+         except ValueError:
+             # value contains more than one @.
+             return False
++        # Max length for domain name labels is 63 characters per RFC 1034.
++        # Helps to avoid ReDoS vectors in the domain part.
++        if len(p2) > 63:
++            return False
+         # Dot must be in p2 (e.g. example.com)
+         if '.' not in p2 or p2.startswith('.'):
+             return False
+@@ -371,9 +377,9 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
+             # Make URL we want to point to.
+             url = None
+             nofollow_attr = ' rel="nofollow"' if nofollow else ''
+-            if simple_url_re.match(middle):
++            if len(middle) <= MAX_URL_LENGTH and simple_url_re.match(middle):
+                 url = smart_urlquote(unescape(middle))
+-            elif simple_url_2_re.match(middle):
++            elif len(middle) <= MAX_URL_LENGTH and simple_url_2_re.match(middle):
+                 url = smart_urlquote('http://%s' % unescape(middle))
+             elif ':' not in middle and is_email_simple(middle):
+                 local, domain = middle.rsplit('@', 1)
+diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py
+index 4c14a47..e373f1a 100644
+--- a/tests/admin_widgets/tests.py
++++ b/tests/admin_widgets/tests.py
+@@ -336,7 +336,12 @@ class AdminSplitDateTimeWidgetTest(SimpleTestCase):
+ class AdminURLWidgetTest(SimpleTestCase):
+     def test_get_context_validates_url(self):
+         w = widgets.AdminURLFieldWidget()
+-        for invalid in ['', '/not/a/full/url/', 'javascript:alert("Danger XSS!")']:
++        for invalid in [
++            "",
++            "/not/a/full/url/",
++            'javascript:alert("Danger XSS!")',
++            "http://" + "한.글." * 1_000_000 + "com",
++        ]:
+             with self.subTest(url=invalid):
+                 self.assertFalse(w.get_context('name', invalid, {})['url_valid'])
+         self.assertTrue(w.get_context('name', 'http://example.com', {})['url_valid'])
+diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py
+index 5abab8d..1956655 100644
+--- a/tests/utils_tests/test_html.py
++++ b/tests/utils_tests/test_html.py
+@@ -254,6 +254,15 @@ class TestUtilsHtml(SimpleTestCase):
+             ),
+             ('[email protected]', '<a href="mailto:[email protected]">[email protected]</a>'),
+         )
++            (
++                "test@" + "한.글." * 15 + "aaa",
++                '<a href="mailto:test@'
++                + "xn--6q8b.xn--bj0b." * 15
++                + 'aaa">'
++                + "test@"
++                + "한.글." * 15
++                + "aaa</a>",
++            ),
+         for value, output in tests:
+             with self.subTest(value=value):
+                 self.assertEqual(urlize(value), output)
+@@ -261,6 +270,10 @@ class TestUtilsHtml(SimpleTestCase):
+     def test_urlize_unchanged_inputs(self):
+         tests = (
+             ('a' + '@a' * 50000) + 'a',  # simple_email_re catastrophic test
++            # Unicode domain catastrophic tests.
++            "a@" + "한.글." * 1_000_000 + "a",
++            "http://" + "한.글." * 1_000_000 + "com",
++            "www." + "한.글." * 1_000_000 + "com",
+             ('a' + '.' * 1000000) + 'a',  # trailing_punctuation catastrophic test
+             'foo@',
+             '@foo.com',
+--
+2.40.0
meta-python/recipes-devtools/python/python3-django_2.2.28.bb +1 -0
index 57ab72bc9..b46fdfc42 100644
@@ -20,6 +20,7 @@ SRC_URI += "file://CVE-2023-31047.patch \
             file://CVE-2024-41989-0003.patch \
             file://CVE-2024-41989-0004.patch \
             file://CVE-2024-41990.patch \
+            file://CVE-2024-41991.patch \
            "
 
 SRC_URI[sha256sum] = "0200b657afbf1bc08003845ddda053c7641b9b24951e52acd51f6abda33a7413"
Signature · 1 line
2.40.0
author
#7 lore raw

PATCH 7/9 python3-django: Fix CVE-2024-45230

In reply to ssambu

From: Soumya Sambu <[email protected]>

An issue was discovered in Django 5.1 before 5.1.1, 5.0 before 5.0.9, and 4.2 before 4.2.16. The urlize() and urlizetrunc() template filters are subject to a potential denial-of-service attack via very large inputs with a specific sequence of characters.

Reference:
https://nvd.nist.gov/vuln/detail/CVE-2024-45230

Upstream-patch:
https://github.com/django/django/commit/d147a8ebbdf28c17cafbbe2884f0bc57e2bf82e2

---
 .../python3-django/CVE-2024-45230.patch       | 137 ++++++++++++++++++
 .../python/python3-django_2.2.28.bb           |   1 +
 2 files changed, 138 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-django/CVE-2024-45230.patch
meta-python/recipes-devtools/python/python3-django/CVE-2024-45230.patch new file +137 -0
new file mode 100644
index 000000000..b3474dc49
@@ -0,0 +1,137 @@
+From d147a8ebbdf28c17cafbbe2884f0bc57e2bf82e2 Mon Sep 17 00:00:00 2001
+From: Sarah Boyce <[email protected]>
+Date: Mon, 12 Aug 2024 15:17:57 +0200
+Subject: [PATCH] [4.2.x] Fixed CVE-2024-45230 -- Mitigated potential DoS in
+ urlize and urlizetrunc template filters.
+
+Thanks MProgrammer (https://hackerone.com/mprogrammer) for the report.
+
+CVE: CVE-2024-45230
+
+Upstream-Status: Backport [https://github.com/django/django/commit/d147a8ebbdf28c17cafbbe2884f0bc57e2bf82e2]
+
+Signed-off-by: Soumya Sambu <[email protected]>
+---
+ django/utils/html.py                          | 22 +++++++++++--------
+ docs/ref/templates/builtins.txt               | 11 ++++++++++
+ .../filter_tests/test_urlize.py               | 22 +++++++++++++++++++
+ tests/utils_tests/test_html.py                |  1 +
+ 4 files changed, 47 insertions(+), 9 deletions(-)
+
+diff --git a/django/utils/html.py b/django/utils/html.py
+index 79f06bd..d129334 100644
+--- a/django/utils/html.py
++++ b/django/utils/html.py
+@@ -1,5 +1,6 @@
+ """HTML utilities suitable for global use."""
+
++import html
+ import json
+ import re
+ from html.parser import HTMLParser
+@@ -327,16 +328,19 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
+             if trailing_punctuation_chars_has_semicolon() and middle.endswith(";"):
+                 # Only strip if not part of an HTML entity.
+                 potential_entity = middle[amp:]
+-                escaped = unescape(potential_entity)
++                escaped = html.unescape(potential_entity)
+                 if escaped == potential_entity or escaped.endswith(";"):
+-                    rstripped = middle.rstrip(";")
+-                    amount_stripped = len(middle) - len(rstripped)
+-                    if amp > -1 and amount_stripped > 1:
+-                        # Leave a trailing semicolon as might be an entity.
+-                        trail = middle[len(rstripped) + 1 :] + trail
+-                        middle = rstripped + ";"
++                    rstripped = middle.rstrip(TRAILING_PUNCTUATION_CHARS)
++                    trail_start = len(rstripped)
++                    amount_trailing_semicolons = len(middle) - len(middle.rstrip(";"))
++                    if amp > -1 and amount_trailing_semicolons > 1:
++                        # Leave up to most recent semicolon as might be an entity.
++                        recent_semicolon = middle[trail_start:].index(";")
++                        middle_semicolon_index = recent_semicolon + trail_start + 1
++                        trail = middle[middle_semicolon_index:] + trail
++                        middle = rstripped + middle[trail_start:middle_semicolon_index]
+                     else:
+-                        trail = middle[len(rstripped) :] + trail
++                        trail = middle[trail_start:] + trail
+                         middle = rstripped
+                     trimmed_something = True
+
+@@ -373,7 +377,7 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
+             url = None
+             nofollow_attr = ' rel="nofollow"' if nofollow else ''
+             if len(middle) <= MAX_URL_LENGTH and simple_url_re.match(middle):
+-                url = smart_urlquote(unescape(middle))
++                url = smart_urlquote(html.unescape(middle))
+             elif len(middle) <= MAX_URL_LENGTH and simple_url_2_re.match(middle):
+                 url = smart_urlquote('http://%s' % unescape(middle))
+             elif ':' not in middle and is_email_simple(middle):
+diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt
+index 4faab38..1990ed0 100644
+--- a/docs/ref/templates/builtins.txt
++++ b/docs/ref/templates/builtins.txt
+@@ -2483,6 +2483,17 @@ Django's built-in :tfilter:`escape` filter. The default value for
+     email addresses that contain single quotes (``'``), things won't work as
+     expected. Apply this filter only to plain text.
+
++.. warning::
++
++    Using ``urlize`` or ``urlizetrunc`` can incur a performance penalty, which
++    can become severe when applied to user controlled values such as content
++    stored in a :class:`~django.db.models.TextField`. You can use
++    :tfilter:`truncatechars` to add a limit to such inputs:
++
++    .. code-block:: html+django
++
++        {{ value|truncatechars:500|urlize }}
++
+ .. templatefilter:: urlizetrunc
+
+ ``urlizetrunc``
+diff --git a/tests/template_tests/filter_tests/test_urlize.py b/tests/template_tests/filter_tests/test_urlize.py
+index 649a965..1991301 100644
+--- a/tests/template_tests/filter_tests/test_urlize.py
++++ b/tests/template_tests/filter_tests/test_urlize.py
+@@ -260,6 +260,28 @@ class FunctionTests(SimpleTestCase):
+             'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>.,:;)&quot;!'
+         )
+
++    def test_trailing_semicolon(self):
++        self.assertEqual(
++            urlize("http://example.com?x=&amp;", autoescape=False),
++            '<a href="http://example.com?x=" rel="nofollow">'
++            "http://example.com?x=&amp;</a>",
++        )
++        self.assertEqual(
++            urlize("http://example.com?x=&amp;;", autoescape=False),
++            '<a href="http://example.com?x=" rel="nofollow">'
++            "http://example.com?x=&amp;</a>;",
++        )
++        self.assertEqual(
++            urlize("http://example.com?x=&amp;;;", autoescape=False),
++            '<a href="http://example.com?x=" rel="nofollow">'
++            "http://example.com?x=&amp;</a>;;",
++        )
++        self.assertEqual(
++            urlize("http://example.com?x=&amp.;...;", autoescape=False),
++            '<a href="http://example.com?x=" rel="nofollow">'
++            "http://example.com?x=&amp</a>.;...;",
++        )
++
+     def test_brackets(self):
+         """
+         #19070 - Check urlize handles brackets properly
+diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py
+index 1a5c963..b382843 100644
+--- a/tests/utils_tests/test_html.py
++++ b/tests/utils_tests/test_html.py
+@@ -289,6 +289,7 @@ class TestUtilsHtml(SimpleTestCase):
+             "&:" + ";" * 100_000,
+             "&.;" * 100_000,
+             ".;" * 100_000,
++            "&" + ";:" * 100_000,
+         )
+         for value in tests:
+             with self.subTest(value=value):
+--
+2.40.0
meta-python/recipes-devtools/python/python3-django_2.2.28.bb +1 -0
index b46fdfc42..275a61622 100644
@@ -21,6 +21,7 @@ SRC_URI += "file://CVE-2023-31047.patch \
             file://CVE-2024-41989-0004.patch \
             file://CVE-2024-41990.patch \
             file://CVE-2024-41991.patch \
+            file://CVE-2024-45230.patch \
            "
 
 SRC_URI[sha256sum] = "0200b657afbf1bc08003845ddda053c7641b9b24951e52acd51f6abda33a7413"
Signature · 1 line
2.40.0
author
#8 lore raw

PATCH 8/9 python3-django: Fix CVE-2024-45231

In reply to ssambu

From: Soumya Sambu <[email protected]>

An issue was discovered in Django v5.1.1, v5.0.9, and v4.2.16. The django.contrib.auth.forms.PasswordResetForm class, when used in a view implementing password reset flows, allows remote attackers to enumerate user e-mail addresses by sending password reset requests and observing the outcome (only when e-mail sending is consistently failing).

Reference:
https://nvd.nist.gov/vuln/detail/CVE-2024-45231

Upstream-patch:
https://github.com/django/django/commit/bf4888d317ba4506d091eeac6e8b4f1fcc731199

---
 .../python3-django/CVE-2024-45231.patch       | 120 ++++++++++++++++++
 .../python/python3-django_2.2.28.bb           |   1 +
 2 files changed, 121 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-django/CVE-2024-45231.patch
meta-python/recipes-devtools/python/python3-django/CVE-2024-45231.patch new file +120 -0
new file mode 100644
index 000000000..2a0925ea9
@@ -0,0 +1,120 @@
+From bf4888d317ba4506d091eeac6e8b4f1fcc731199 Mon Sep 17 00:00:00 2001
+From: Natalia <[email protected]>
+Date: Mon, 19 Aug 2024 14:47:38 -0300
+Subject: [PATCH] [4.2.x] Fixed CVE-2024-45231 -- Avoided server error on
+ password reset when email sending fails.
+
+On successful submission of a password reset request, an email is sent
+to the accounts known to the system. If sending this email fails (due to
+email backend misconfiguration, service provider outage, network issues,
+etc.), an attacker might exploit this by detecting which password reset
+requests succeed and which ones generate a 500 error response.
+
+Thanks to Thibaut Spriet for the report, and to Mariusz Felisiak, Adam
+Johnson, and Sarah Boyce for the reviews.
+
+CVE: CVE-2024-45231
+
+Upstream-Status: Backport [https://github.com/django/django/commit/bf4888d317ba4506d091eeac6e8b4f1fcc731199]
+
+Signed-off-by: Soumya Sambu <[email protected]>
+---
+ django/contrib/auth/forms.py   |  9 ++++++++-
+ docs/topics/auth/default.txt   |  4 +++-
+ tests/auth_tests/test_forms.py | 21 +++++++++++++++++++++
+ tests/mail/custombackend.py    |  5 +++++
+ 4 files changed, 37 insertions(+), 2 deletions(-)
+
+diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py
+index 26d3ca7..dc640a5 100644
+--- a/django/contrib/auth/forms.py
++++ b/django/contrib/auth/forms.py
+@@ -1,3 +1,4 @@
++import logging
+ import unicodedata
+
+ from django import forms
+@@ -18,6 +19,7 @@ from django.utils.text import capfirst
+ from django.utils.translation import gettext, gettext_lazy as _
+
+ UserModel = get_user_model()
++logger = logging.getLogger("django.contrib.auth")
+
+
+ def _unicode_ci_compare(s1, s2):
+@@ -264,7 +266,12 @@ class PasswordResetForm(forms.Form):
+             html_email = loader.render_to_string(html_email_template_name, context)
+             email_message.attach_alternative(html_email, 'text/html')
+
+-        email_message.send()
++        try:
++            email_message.send()
++        except Exception:
++            logger.exception(
++                "Failed to send password reset email to %s", context["user"].pk
++            )
+
+     def get_users(self, email):
+         """Given an email, return matching user(s) who should receive a reset.
+diff --git a/docs/topics/auth/default.txt b/docs/topics/auth/default.txt
+index 1af4951..6fdf700 100644
+--- a/docs/topics/auth/default.txt
++++ b/docs/topics/auth/default.txt
+@@ -1530,7 +1530,9 @@ provides several built-in forms located in :mod:`django.contrib.auth.forms`:
+     .. method:: send_mail(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None)
+
+         Uses the arguments to send an ``EmailMultiAlternatives``.
+-        Can be overridden to customize how the email is sent to the user.
++        Can be overridden to customize how the email is sent to the user. If
++        you choose to override this method, be mindful of handling potential
++        exceptions raised due to email sending failures.
+
+         :param subject_template_name: the template for the subject.
+         :param email_template_name: the template for the email body.
+diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py
+index e73d4b8..a45fd70 100644
+--- a/tests/auth_tests/test_forms.py
++++ b/tests/auth_tests/test_forms.py
+@@ -935,6 +935,27 @@ class PasswordResetFormTest(TestDataMixin, TestCase):
+             message.get_payload(1).get_payload()
+         ))
+
++    @override_settings(EMAIL_BACKEND="mail.custombackend.FailingEmailBackend")
++    def test_save_send_email_exceptions_are_catched_and_logged(self):
++        (user, username, email) = self.create_dummy_user()
++        form = PasswordResetForm({"email": email})
++        self.assertTrue(form.is_valid())
++
++        with self.assertLogs("django.contrib.auth", level=0) as cm:
++            form.save()
++
++        self.assertEqual(len(mail.outbox), 0)
++        self.assertEqual(len(cm.output), 1)
++        errors = cm.output[0].split("\n")
++        pk = user.pk
++        self.assertEqual(
++            errors[0],
++            f"ERROR:django.contrib.auth:Failed to send password reset email to {pk}",
++        )
++        self.assertEqual(
++            errors[-1], "ValueError: FailingEmailBackend is doomed to fail."
++        )
++
+     @override_settings(AUTH_USER_MODEL='auth_tests.CustomEmailField')
+     def test_custom_email_field(self):
+         email = '[email protected]'
+diff --git a/tests/mail/custombackend.py b/tests/mail/custombackend.py
+index fd57777..3e161d1 100644
+--- a/tests/mail/custombackend.py
++++ b/tests/mail/custombackend.py
+@@ -13,3 +13,8 @@ class EmailBackend(BaseEmailBackend):
+         # Messages are stored in an instance variable for testing.
+         self.test_outbox.extend(email_messages)
+         return len(email_messages)
++
++
++class FailingEmailBackend(BaseEmailBackend):
++    def send_messages(self, email_messages):
++        raise ValueError("FailingEmailBackend is doomed to fail.")
+--
+2.40.0
meta-python/recipes-devtools/python/python3-django_2.2.28.bb +1 -0
index 275a61622..4444d943c 100644
@@ -22,6 +22,7 @@ SRC_URI += "file://CVE-2023-31047.patch \
             file://CVE-2024-41990.patch \
             file://CVE-2024-41991.patch \
             file://CVE-2024-45230.patch \
+            file://CVE-2024-45231.patch \
            "
 
 SRC_URI[sha256sum] = "0200b657afbf1bc08003845ddda053c7641b9b24951e52acd51f6abda33a7413"
Signature · 1 line
2.40.0
author
#9 lore raw

PATCH 9/9 python3-django: Fix CVE-2024-53907

In reply to ssambu

From: Soumya Sambu <[email protected]>

An issue was discovered in Django 5.1 before 5.1.4, 5.0 before 5.0.10, and 4.2 before 4.2.17. The strip_tags() method and striptags template filter are subject to a potential denial-of-service attack via certain inputs containing large sequences of nested incomplete HTML entities.

Reference:
https://nvd.nist.gov/vuln/detail/CVE-2024-53907

Upstream-patch:
https://github.com/django/django/commit/790eb058b0716c536a2f2e8d1c6d5079d776c22b

---
 .../python3-django/CVE-2024-53907.patch       | 92 +++++++++++++++++++
 .../python/python3-django_2.2.28.bb           |  1 +
 2 files changed, 93 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-django/CVE-2024-53907.patch
meta-python/recipes-devtools/python/python3-django/CVE-2024-53907.patch new file +92 -0
new file mode 100644
index 000000000..5a6af7061
@@ -0,0 +1,92 @@
+From 790eb058b0716c536a2f2e8d1c6d5079d776c22b Mon Sep 17 00:00:00 2001
+From: Sarah Boyce <[email protected]>
+Date: Wed, 13 Nov 2024 15:06:23 +0100
+Subject: [PATCH] [4.2.x] Fixed CVE-2024-53907 -- Mitigated potential DoS in
+ strip_tags().
+
+Thanks to jiangniao for the report, and Shai Berger and Natalia Bidart
+for the reviews.
+
+CVE: CVE-2024-53907
+
+Upstream-Status: Backport [https://github.com/django/django/commit/790eb058b0716c536a2f2e8d1c6d5079d776c22b]
+
+Signed-off-by: Soumya Sambu <[email protected]>
+
+---
+ django/utils/html.py           | 10 ++++++++--
+ tests/utils_tests/test_html.py |  7 +++++++
+ 2 files changed, 15 insertions(+), 2 deletions(-)
+
+diff --git a/django/utils/html.py b/django/utils/html.py
+index 3cf1bfc..0d5ffd2 100644
+--- a/django/utils/html.py
++++ b/django/utils/html.py
+@@ -8,12 +8,14 @@ from urllib.parse import (
+     parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit,
+ )
+ 
++from django.core.exceptions import SuspiciousOperation
+ from django.utils.functional import Promise, keep_lazy, keep_lazy_text
+ from django.utils.http import RFC3986_GENDELIMS, RFC3986_SUBDELIMS
+ from django.utils.safestring import SafeData, SafeText, mark_safe
+ from django.utils.text import normalize_newlines
+ 
+ MAX_URL_LENGTH = 2048
++MAX_STRIP_TAGS_DEPTH = 50
+ 
+ # Configuration for urlize() function.
+ TRAILING_PUNCTUATION_CHARS = '.,:;!'
+@@ -185,15 +187,19 @@ def _strip_once(value):
+ @keep_lazy_text
+ def strip_tags(value):
+     """Return the given HTML with all tags stripped."""
+-    # Note: in typical case this loop executes _strip_once once. Loop condition
+-    # is redundant, but helps to reduce number of executions of _strip_once.
+     value = str(value)
++    # Note: in typical case this loop executes _strip_once twice (the second
++    # execution does not remove any more tags).
++    strip_tags_depth = 0
+     while '<' in value and '>' in value:
++        if strip_tags_depth >= MAX_STRIP_TAGS_DEPTH:
++            raise SuspiciousOperation
+         new_value = _strip_once(value)
+         if value.count('<') == new_value.count('<'):
+             # _strip_once wasn't able to detect more tags.
+             break
+         value = new_value
++        strip_tags_depth += 1
+     return value
+ 
+ 
+diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py
+index 8fe2f24..2f412e1 100644
+--- a/tests/utils_tests/test_html.py
++++ b/tests/utils_tests/test_html.py
+@@ -1,6 +1,7 @@
+ import os
+ from datetime import datetime
+ 
++from django.core.exceptions import SuspiciousOperation
+ from django.test import SimpleTestCase
+ from django.utils.functional import lazystr
+ from django.utils.html import (
+@@ -90,12 +91,18 @@ class TestUtilsHtml(SimpleTestCase):
+             ('<script>alert()</script>&h', 'alert()h'),
+             ('><!' + ('&' * 16000) + 'D', '><!' + ('&' * 16000) + 'D'),
+             ('X<<<<br>br>br>br>X', 'XX'),
++            ("<" * 50 + "a>" * 50, ""),
+         )
+         for value, output in items:
+             with self.subTest(value=value, output=output):
+                 self.check_output(strip_tags, value, output)
+                 self.check_output(strip_tags, lazystr(value), output)
+ 
++    def test_strip_tags_suspicious_operation(self):
++        value = "<" * 51 + "a>" * 51, "<a>"
++        with self.assertRaises(SuspiciousOperation):
++            strip_tags(value)
++
+     def test_strip_tags_files(self):
+         # Test with more lengthy content (also catching performance regressions)
+         for filename in ('strip_tags1.html', 'strip_tags2.txt'):
meta-python/recipes-devtools/python/python3-django_2.2.28.bb +1 -0
index 4444d943c..0478fd388 100644
@@ -23,6 +23,7 @@ SRC_URI += "file://CVE-2023-31047.patch \
             file://CVE-2024-41991.patch \
             file://CVE-2024-45230.patch \
             file://CVE-2024-45231.patch \
+            file://CVE-2024-53907.patch \
            "
 
 SRC_URI[sha256sum] = "0200b657afbf1bc08003845ddda053c7641b9b24951e52acd51f6abda33a7413"
Signature · 1 line
2.40.0